import React from "react";
import PubSub from "pubsub-js";
import { useEffect } from "react";
import { useState } from "react";
import axios from 'axios';
import {Link, useNavigate} from 'react-router-dom'

export default function HeroList() {
  //创建英雄数据状态
  let [heros, setHeros] = useState([]);
  //创建第一次显示状态
  let [isFirst, setIsFirst] = useState(true);
  //声明状态
  let [isLoading, setIsLoading] = useState(false);
  //调用函数, 获得 navigate 函数
  let navigate = useNavigate();

  //组件挂载完毕
  useEffect(() => {
    PubSub.subscribe("keyword", async (channel, data) => {
      //修改 isFirst 状态
      setIsFirst(false);
      setIsLoading(true);
      //清空英雄数据
      setHeros([]);
      // http://api.xiaohigh.com/heros?name_like=张
      let result = await axios.get('http://api.xiaohigh.com/heros', {
        params: {
          name_like: data
        }
      });
      //更新 heros 数据
      setHeros(result.data);
      setIsLoading(false);
    });
    //取消订阅
    return () => {
      PubSub.unsubscribe('keyword');
    }
  }, []);
  return (
    <div className="row">
      {isFirst && <h3 className="text-center">欢迎来到王者荣耀~~</h3>}
      {/* 英雄列表 */}
      {heros.map((item) => {
        return (
          <div className="col-xs-1" key={item.id}>
            <img
              className="img-responsive"
              src={`http://cdn.xiaohigh.com${item.image}`}
              alt=""
              onClick={() => {
                //1. params 传参
                // navigate(`/hero/${item.id}`)
                //2. query 传参
                // navigate(`/hero?id=${item.id}`)
                //3. state 传参
                navigate('/hero', {
                  //替换模式
                  replace: false,
                  state: {
                    id: item.id
                  }
                })
              }}
            />
            <p className="text-center">{item.name}</p>
          </div>
        );
      })}

      {/* 暂无数据 */}
      {
        (heros.length === 0 && !isFirst && !isLoading) 
        ? 
        <p className="text-center">暂无数据</p> 
        : ''}

      {/* 加载中.. */}
      {
        isLoading  && <h3 className="text-center">搜索中.....</h3>
      }
      
    </div>
  );
}
